package com.unity.notificationbackground;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import java.util.HashMap;
import java.util.Map;


public class AndroidBackgroundNotificationManager {

    public static final int RETURN_NONE = -1;
    public static final int RETURN_APP = 0;
    public static final int RETURN_NET = 1;

    private Context _context;
    private Activity _activity;
    private Intent _intent;
    private NotificationManager _notificationManager;
    private static AndroidBackgroundNotificationManager _instance;
    public static final String DefaultHighChannel = "IMPORTANCE_HIGH";
    public static final String DefaultMaxChannel = "IMPORTANCE_MAX";

    public static AndroidBackgroundNotificationManager GetInstance() {
        return _instance;
    }
    private BackgroundNotificationTask _task;
//    public HashMap<Integer, BackgroundNotificationTask> MapProgressAsyncTask = new HashMap<Integer, BackgroundNotificationTask>();
    public HashMap<Integer, IBackgroundNotification> Notificaitons = new HashMap<Integer, IBackgroundNotification>();

    public AndroidBackgroundNotificationManager(Activity activity) {
        _instance = this;
        _activity = activity;
        _context = activity.getApplicationContext();
        _intent = _activity.getIntent();
        _notificationManager = GetNotificationManager(_context);

        RegisterNotificationChannels();
    }

    public void ScheduleBackgroundNotification(IBackgroundNotification progressNotify) {
        if (_task== null)
        {
            _task = new BackgroundNotificationTask();
            _task.execute(1000);
        }
        if (Notificaitons.containsKey(progressNotify.GetId())) {
            Notificaitons.remove(progressNotify.GetId());
        }
//        BackgroundNotificationTask task = new BackgroundNotificationTask(progressNotify);
        Notificaitons.put(progressNotify.GetId(), progressNotify);
//        task.execute(1000);
    }

    public void CancelScheduleBackgroundNotification(IBackgroundNotification progressNotify) {
        if (!Notificaitons.containsKey(progressNotify.GetId())) {
            return;
        }
//        BackgroundNotificationTask task = MapProgressAsyncTask.get(progressNotify.GetId());
        Notificaitons.remove(progressNotify.GetId());
//        task.cancel(true);
        CancelDisplayedNotification(progressNotify.GetId());
    }

    public void CancelAllScheduleBackgroundNotification() {
        for (Map.Entry<Integer, IBackgroundNotification> entry : Notificaitons.entrySet()) {
//            entry.getValue().cancel(true);
            CancelDisplayedNotification(entry.getKey());
        }
        Notificaitons.clear();
        if (_task!= null)
        {
            _task.cancel(true);
            _task = null;
        }
    }


    @SuppressWarnings("deprecation")
    public Notification.Builder SendNotification(String title, String content) {
        int id = 0;
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            builder = new Notification.Builder(_context);
        } else {
            builder = new Notification.Builder(_context, DefaultMaxChannel);
        }
        builder.setContentTitle(title);
        builder.setContentText(content);
        builder.setSmallIcon(GetDefaultAppIcon());
        builder.setPriority(Notification.PRIORITY_HIGH);
        builder.setAutoCancel(true);
        _notificationManager.notify(id, builder.build());
        return builder;
    }

    public void CancelDisplayedNotification(int id) {
        _notificationManager.cancel(id);
    }

    // Cancel all previously shown notifications.
    public void CancelAllNotifications() {
        CancelAllScheduleBackgroundNotification();
        _notificationManager.cancelAll();
    }

    private void RegisterNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(DefaultHighChannel, DefaultHighChannel, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            channel.enableVibration(false);
            channel.setSound(null,null);
            _notificationManager.createNotificationChannel(channel);


            @SuppressLint("WrongConstant")
            NotificationChannel channel2 = new NotificationChannel(DefaultMaxChannel, DefaultMaxChannel, NotificationManager.IMPORTANCE_MAX);
            channel2.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            channel2.enableLights(true);
            channel2.enableVibration(true);
//            channel2.setVibrationPattern(new long[]{0,1000});
            _notificationManager.createNotificationChannel(channel2);
        }
    }

    public int GetDefaultAppIcon() {
        return GetDefaultAppIcon(_context);
    }

    public void SendBackgroundNotification(int id, Notification notification) {
        _notificationManager.notify(id,notification);
    }


    public  Notification.Builder NewBuilder(int priority)
    {
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            builder = new Notification.Builder(_context);
        } else {
            if (priority>= Notification.PRIORITY_MAX)
            {
                builder = new Notification.Builder(_context, DefaultMaxChannel);
            }else
            {
                builder = new Notification.Builder(_context, DefaultHighChannel);
            }

        }
        return builder;
    }

    public Notification.Builder SettingNotification(Notification.Builder builder,IBackgroundNotification progressNotify) {
        int id = progressNotify.GetId();
        builder.setSmallIcon(GetDefaultAppIcon());
        PendingIntent pendingIntent;
        pendingIntent = GetActivityPendingIntent(_activity, id, GetOpenAppIntent(), PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (progressNotify.GetChannelId() >= Notification.PRIORITY_MAX)
            {
                builder.setChannelId(DefaultMaxChannel);
            }else{
                builder.setChannelId(DefaultHighChannel);
            }
        }
        builder.setContentTitle(progressNotify.GetTitle());
        builder.setContentText(progressNotify.GetContent());
        builder.setContentIntent(pendingIntent);
        if (progressNotify.GetChannelId() >= Notification.PRIORITY_MAX)
        {
            builder.setPriority(Notification.PRIORITY_MAX);
            builder.setOngoing(true);
        }else{
            builder.setPriority(Notification.PRIORITY_DEFAULT);
            builder.setOngoing(false);
        }
        builder.setAutoCancel(true);
        builder.setDefaults(Notification.DEFAULT_ALL);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);
//            builder.setFlag(Notification.FLAG_SHOW_LIGHTS,true);
        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            RemoteViews headsUpView = new RemoteViews(_activity.getPackageName(), R.layout.layout_heads_up_notification);
//            builder.setCustomHeadsUpContentView(headsUpView);
//        }
//        builder.build().flags = Notification.FLAG_NO_CLEAR;
//        builder.fa(Notification.FLAG_NO_CLEAR, true);
        return builder;
    }

    private Intent GetOpenWifiIntent() {
        return new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
    }

    public Intent GetOpenAppIntent() {
        Intent openAppIntent = new Intent(_context, _activity.getClass());
        openAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return openAppIntent;
    }

    public static NotificationManager GetNotificationManager(Context context) {
        return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public static int GetDefaultAppIcon(Context context) {
        return context.getApplicationInfo().icon;
    }

    public static PendingIntent GetActivityPendingIntent(Context context, int id, Intent intent, int flags) {
        if (Build.VERSION.SDK_INT >= 23)
            return PendingIntent.getActivity(context, id, intent, flags | PendingIntent.FLAG_IMMUTABLE);
        else
            return PendingIntent.getActivity(context, id, intent, flags);
    }

    public static AndroidBackgroundNotificationManager NotificationManagerImpl(Activity activity) {
        return new AndroidBackgroundNotificationManager(activity);
    }
}
